package com.atguigu.srb.core.controller.admin;


import com.alibaba.excel.EasyExcel;
import com.atguigu.srb.base.exception.SrbException;
import com.atguigu.srb.base.result.ResponseEnum;
import com.atguigu.srb.base.result.ResponseVo;
import com.atguigu.srb.base.util.SrbAssert;
import com.atguigu.srb.core.pojo.entity.Dict;
import com.atguigu.srb.core.pojo.vo.DictExcelVO;
import com.atguigu.srb.core.service.DictService;
import io.swagger.annotations.ApiOperation;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 数据字典 前端控制器
 * </p>
 *
 * @author Atguigu
 * @since 2023-03-25
 */
@RestController
//@CrossOrigin
@RequestMapping("/admin/core/dict")
public class AdminDictController {
    @Resource
    DictService dictService;

    @ApiOperation("根据一级数据字典dictCode查询二级数据字典集合")
    @GetMapping("list/{dictCode}")
    public ResponseVo listByDictCode(@PathVariable("dictCode")String dictCode){
        List<Dict> dicts = dictService.getByDictCode(dictCode);
        return ResponseVo.ok().data("items" , dicts);
    }

    @ApiOperation("新增数据字典")
    @PostMapping
    public ResponseVo save(@RequestBody Dict dict){
        dictService.saveChildDict(dict);

        return ResponseVo.ok().message("新增成功");
    }
    @ApiOperation("更新数据字典")
    @PutMapping
    public ResponseVo updateById(@RequestBody Dict dict){
        dictService.updateById(dict);
        return ResponseVo.ok().message("更新成功");
    }
    @ApiOperation("根据id查询数据字典")
    @GetMapping("{id}") //http://localhost:8110/admin/core/dict/30000
    public ResponseVo getById(@PathVariable("id")Long id){
        return ResponseVo.ok().data("item",dictService.getById(id));
    }
    @ApiOperation("根据id删除")
    @DeleteMapping("{id}")
    public ResponseVo deleteById(@PathVariable("id")Long id){
        //如果要删除的数据字典有下一级 不能删除
        SrbAssert.assertNotTrue(dictService.hasChildren(id),ResponseEnum.HAS_CHILDREN_ERROR);
        //删除
        SrbAssert.assertTrue(dictService.removeById(id),ResponseEnum.ERROR);
        return ResponseVo.ok().message("删除成功");
    }


    @ApiOperation("根据父id查询数据字典和它是否有下一级数据字典的集合")
    @GetMapping("parent/{pid}")//使用pid查询一组数据字典(一级数据字典pid=0)
    public ResponseVo parent(@PathVariable("pid")Long pid){
        List<Dict> dicts = dictService.parent(pid);
        return ResponseVo.ok().data("items",dicts);
    }


    /*
        处理上传的数据字典excel：解析excel数据保存到数据字典表 每一行代表一个数据字典对象
        1、创建javabean接收excel数据
        2、创建回调监听器：处理解析到的每行数据
        3、使用EasyExcel读取数据
     */
    //必须不能使用get方式：文件上传使用的是请求体
    @ApiOperation("导入数据字典")
    @PostMapping("import") //前端上传文件的表单项name值需要设置为file 默认方式才可以接受
    public ResponseVo importDicts(@RequestParam("excel") MultipartFile file){
        dictService.importDicts(file);
        return ResponseVo.ok().message("文件上传成功");
    }
    //文件下载
    @ApiOperation("导出数据字典")
    @GetMapping("export")
    public void exportDicts(HttpServletResponse response){
        try {
            //设置响应报文响应体内容的类型+编码+文件名
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName= URLEncoder.encode("数据字典_"+new DateTime().toString("yyyy-MM-dd-HH-mm-ss"),"UTF-8").replaceAll("\\+","%20");
            response.setHeader("Content-disposition","attachment;filename*=utf-8''"+fileName+".xlsx");
            //查询数据
            List<DictExcelVO> dictExcelVOS = dictService.list().stream().map(dict -> {
                DictExcelVO vo = new DictExcelVO();
                BeanUtils.copyProperties(dict, vo);
                return vo;
            }).collect(Collectors.toList());

            //向response对象的输出流中写数据
            EasyExcel.write(response.getOutputStream())
                    .sheet("数据字典")
                    .head(DictExcelVO.class)
                    .doWrite(dictExcelVOS);
        } catch (Exception e) {
            e.printStackTrace();
            throw new SrbException(ResponseEnum.EXPORT_DATA_ERROR);
        }
    }
}

